<!-- chat/templates/chat/room.html -->

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>聊天室{{ room_name }}</title>
</head>
<body>
<label for="chat-log">聊天屏幕：</label><textarea id="chat-log" cols="100" rows="20"></textarea>
<br>

<label for="chat-message-input">发送信息：</label><input id="chat-message-input" type="text" size="100">
<input id="chat-message-submit" type="button" value="发 送">
{{ room_name|json_script:"room-name" }}
<script>
    const roomName = JSON.parse(document.getElementById('room-name').textContent);
    const chatSocket = new WebSocket('ws://' + window.location.host + '/ws/chat/' + roomName + '/');
    {# 接收数据 #}
    chatSocket.onmessage = function (e) {
        console.log(e)
        const data = JSON.parse(e.data);
        document.querySelector('#chat-log').value += (data.username + ": " + data.message + '\n\n');
    };
    {# 关闭时触发 #}
    chatSocket.onclose = function (e) {
        console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#chat-message-input').focus();
    document.querySelector('#chat-message-input').onkeyup = function (e) {
        if (e.keyCode === 13) {  // enter, return
            document.querySelector('#chat-message-submit').click();
        }
    };
    document.querySelector('#chat-message-submit').onclick = function (e) {
        const messageInputDom = document.querySelector('#chat-message-input');
        const message = messageInputDom.value;
        {# 发送数据到websocket服务端 #}
        chatSocket.send(JSON.stringify({
            'message': message
        }));
        messageInputDom.value = '';
    };
</script>

</body>

</html>